package com.eslserver.dao;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Collection;

import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.to.ESL;
import com.eslserver.to.wrapper.ESLCollectionPageWrapper;
import com.eslserver.util.HibernateUtil;

public class DBESLDAO implements ESLDAO {
	public static final Logger LOG = LoggerFactory.getLogger(DBESLDAO.class);

	protected DBESLDAO() throws SQLException {
		// Empty protected constructor to avoid unnecessary initialization
	}

	@Override
	public ESL addESL(ESL esl) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.save(esl);
		return esl;
	}

	@Override
	public void updateESL(ESL esl) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.update(esl);
	}

	@Override
	public ESL loadESL(Integer eslID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		ESL esl = (ESL) session.load(ESL.class, eslID);
		return esl;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<ESL> loadAllESLs() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		ESL esl = ESL.createESL();
		esl.setDelete(false);

		Example example = Example.create(esl);

		Collection<ESL> eslCollection = session.createCriteria(ESL.class)
				.add(example).list();

		return eslCollection;
	}

	@Override
	public void deleteESL(Integer eslID) {
		ESL esl = loadESL(eslID);
		if (esl != null) {
			// esl.setGroupID(null);
			esl.setDelete(true);
			updateESL(esl);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public ESLCollectionPageWrapper<ESL> loadESLByPageQuery(String sQuery,
			String aQuery) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();

		ESLCollectionPageWrapper<ESL> eslCollectionPageWrapper = new ESLCollectionPageWrapper<ESL>();

		Collection<ESL> eslCollection = session.createSQLQuery(sQuery)
				.addEntity(ESL.class).list();

		String foundQuery = aQuery;
		BigInteger foundCount = (BigInteger) session.createSQLQuery(foundQuery)
				.uniqueResult();
		eslCollectionPageWrapper.setFilteredTotal(foundCount.intValue());

		String allQuery = "SELECT COUNT(*) FROM ESL WHERE isDelete=false";
		BigInteger allCount = (BigInteger) session.createSQLQuery(allQuery)
				.uniqueResult();
		eslCollectionPageWrapper.setTotal(allCount.intValue());

		eslCollectionPageWrapper.getESLCollection().addAll(eslCollection);

		return eslCollectionPageWrapper;
	}
}
